package com.fjwt.gz.province.changchun;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.core.third.bo.RealnameBo;
import com.fjwt.gz.core.third.interfaces.RealNameAuthInterface;
import com.fjwt.gz.province.changchun.encrypt.AesUtil;
import com.fjwt.gz.province.changchun.encrypt.ChangchunKit;
import com.fjwt.gz.province.changchun.encrypt.SignVerifyFilter;
import com.fjwt.gz.province.changchun.encrypt.SignatureUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class JilinRealNameAuthService extends RealNameAuthInterface {


    @Override
    @Transactional
    public JSONObject realNameAuth(RealnameBo realnameBo){
        log.info("长春请求实名认证接口进来的参数是：{}",JSONUtil.toJsonStr(realnameBo));
        if (!realnameBo.getLocationAgentNo().equals("41000122")&&!realnameBo.getLocationAgentNo().equals("22011060")){
            throw new BizException("抱歉,该地区暂不支持实名认证");
        }
        HttpResponse response =null;
        try {
            Map map = new HashMap();
            map.put("custNm", AesUtil.encrypt(realnameBo.getName()));
            map.put("moblNum", AesUtil.encrypt(realnameBo.getPhone()));
            map.put("mediumNo", AesUtil.encrypt(realnameBo.getBankCard()));
            String sign = SignatureUtil.generateSignature(map, SignVerifyFilter.SECRET_KEY);
            Boolean a = SignatureUtil.verifySignature(map, SignVerifyFilter.SECRET_KEY, sign);
            log.debug("验签结果：" + a);
            String url = ChangchunKit.REAL_NAME_AUTH_URL;
            log.info("长春请求实名认证接口请求地址：{}，请求参数：{}",url,JSONUtil.toJsonStr(map));
             response = HttpRequest.post(url)
                    .header("Content-Type", "multipart/form-data")
                    .header("auth-sign", sign)
                    .timeout(20000)
                    .form(map)
                    .execute();
        }catch (Exception e){
            e.printStackTrace();
            throw new BizException("网络连接异常,请稍后重试");
        }
        if(response==null){
            throw new BizException("网络连接异常,请稍后重试");
        }
        JSONObject respData = JSONObject.parseObject(response.body());
        log.info("长春请求实名认证接口返回数据respData:{}", JSONUtil.toJsonStr(respData));
        if (ObjectUtils.isEmpty(respData)){
            throw new BizException("请求接口返回数据为空");
        }
        //TODO 注意：此刻返回的是所有数据，这里没有对code做任何校验，到上面一层进行处理
        //TODO 上面一层处理时需注意：返回的数据有需要存储到数据库，记得保存数据库，参照老版的
        return respData;
    }


}
